<template lang="pug">
  .attachments-gallery(style="position:relative")
    v-overlay(absolute v-if="isLoading")
      v-progress-circular(indeterminate color="gray")
    ImagePreviewGallery(ref="imagePreviewGallery" :images="imageAttachments.map(x => x.downloadUrl)")
    .row.pa-1
      .pa-2.col-2(v-for="(item, index) in imageAttachments" )
        v-card.img-pod(role="button" @click="togglePreview(item, index)")

          // v-img(width="340" height="240" :src="'https://picsum.photos/'+randomRatio()+'?random='+ item.id")
          v-img(width="100%" aspect-ratio="1" :src="item.previewUrl")
          v-card-subtitle.img-name(:alt="item.name") {{item.name}}
          v-divider
          v-card-actions
            v-spacer
            v-btn(icon v-show="canDelete(item)" @click.stop="deleteAttachment(item)")
              v-icon delete

    h3.my-4 其他文件
    v-divider
    v-simple-table(:height="listHeight" fixed-header=true)
      template(v-slot:default)
        thead
          th.text-left 文件名
          th.text-left 文件大小
          th.text-left 上传时间
          th.text-left 操作
        tbody
          tr(v-for="item in otherAttachmetns" :key="item.id")
            td
              a(:href="item.downloadUrl" download) {{item.name}}
            td {{formatBytes(item.size)}}
            td {{formatDate(item.created_at)}} {{item.upload_by}}
            td
              v-btn(icon v-show="canDelete(item)" @click="deleteAttachment(item)")
                v-icon delete
</template>

<script lang="ts">
  import Vue, {VueConstructor} from 'vue'
  import {isEmpty, get, orderBy} from 'lodash'
  import {AttachableType, Attachment} from '@/store/modules/types/Attachment'
  import ImagePreviewGallery from '@/components/widgets/image_preview/image_preview_gallery.vue'

  import {url, formatDateTime} from '@/store/utils'
  import {mapState} from 'vuex'

  export default (Vue as VueConstructor<Vue & {
    attachments: Array<Attachment>,
    isLoading: boolean,
    reset: () => void,
    refresh: () => void
    $refs: {
      imagePreviewGallery: ImagePreviewGallery
    },
  }>).extend({
    name: 'attachments_gallery',

    props: {
      attachableType: String,
      attachableId: Number
    },
    methods: {
      deleteAttachment(item: Attachment) {
        this.$confirm({
          body: '确认删除？'
        }).then(()=> this.doDelete(item))
      },
      doDelete(item: Attachment){
        axios.post(url(`/api/attachments/delete/${item.id}`)).then(this.refresh)
      },
      canDelete(item: Attachment) {
        return this.me.id == item.upload_by
      },
      togglePreview(item: Attachment, index: number) {
        this.$refs.imagePreviewGallery.toggle(index)
      },
      randomRatio() {
        let v1 = Math.floor(Math.random() * 1000)
        let v2 = Math.floor(Math.random() * 1000)
        return `${v1}/${v1}`
      },
      isValidProps() {
        return !isEmpty(this.attachableId)
      },
      formatDate(s: string) {
        return formatDateTime(s)
      },
      formatBytes(bytes: number, decimals = 0) {
        if (bytes === 0) return '0 Bytes'

        const k = 1024
        const dm = decimals < 0 ? 0 : decimals
        const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']

        const i = Math.floor(Math.log(bytes) / Math.log(k))

        return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]
      },
      reset() {
        this.attachments = []
      },
      async refresh() {
        if (this.isLoading) {
          return
        }
        this.isLoading = true
        let response = await axios.post(url('/api/attachments/list'), {
          'attachable_id': this.attachableId,
          'attachable_type': this.attachableType
        }).finally(() => this.isLoading = false)
        this.attachments = get(response, 'data.result', [])
      }
    },
    watch: {
      attachableId: {
        handler() {
          this.reset()
          this.refresh()
        },
        immediate: true
      }
    },
    computed: {
      ...mapState('app', ['me']),
      listHeight() {
        return this.attachments.length > 10 ? 500 : 'auto'
      },
      imageAttachments(): Attachment[] {
        return orderBy(this.attachments.filter(({ type }: { type: string }) => /jpeg|png/.test(type)), ['created_at'], ['desc'])
      },
      otherAttachmetns() {
        return orderBy(this.attachments.filter(({ type }: { type: string }) => !/jpeg|png/.test(type)), ['created_at'], ['desc'])
      },
    },
    components: { ImagePreviewGallery },
    data() {
      return {
        attachments: [] as Attachment[],
        ossEndPoint: '',
        isLoading: false
      }
    },
    mounted(): void {
    }
  })
</script>

<style lang="scss">
  .attachments-gallery {
    .img-name {
      width: 100%;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }
  }
</style>